import django_filters
from main.filters import NumberInFilter
from main.models import Warranty
from main.permissions import DjangoModelFullPermissions
from rest_framework import serializers, viewsets


class WarrantySerializer(serializers.ModelSerializer):
    contract = serializers.PrimaryKeyRelatedField(
        read_only=True, required=False
    )
    attachs = serializers.SerializerMethodField(read_only=True, required=False)

    def get_attachs(self, obj):
        return obj.attachs.count()

    class Meta:
        model = Warranty
        fields = (
            "id",
            "name",
            "end_date",
            "note",
            "created_on",
            "updated_on",
            "contract",
            "attachs",
        )


class WarrantyFilter(django_filters.FilterSet):
    ids = NumberInFilter(field_name="id", lookup_expr="in")

    class Meta:
        model = Warranty
        fields = ("id",)


class WarrantyViewSet(viewsets.ModelViewSet):
    queryset = Warranty.objects.all()
    serializer_class = WarrantySerializer
    permission_classes = (DjangoModelFullPermissions,)
    filterset_class = WarrantyFilter
